package com.hmjk.health.home;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.FocusFragment;
import com.hmjk.health.IndexActivity;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.HttpConf;
import com.hmjk.health.background.NetService;
import com.hmjk.health.card.CardsActivity;
import com.hmjk.health.card.InterestDeviceDialog;
import com.hmjk.health.card.NewDeviceActivity;
import com.hmjk.health.card.InterestDeviceDialog.OnInterestDialogDismissListener;
import com.hmjk.health.health.HealthCardsActivity;
import com.hmjk.health.health.HealthHomeFragment;
import com.hmjk.health.health.HealthScheduleFragment;
import com.hmjk.health.map.MapActivity;
import com.hmjk.health.setting.SettingActivity;
import com.hmjk.health.setting.SettingsConstants;
import com.hmjk.health.user.ApplyFamilyDialog;
import com.hmjk.health.user.ApplyFamilyDialog.OnApplyDialogDismissListener;
import com.hmjk.health.user.ToDoActivity;
import com.hmjk.health.user.UserDetailActivity;
import com.hmjk.health.util.*;
import com.hmjk.health.views.BeautyButton;
import com.hmjk.health.views.RightSidePopMenu;
import com.hmjk.health.views.RightSidePopMenu.OnPopMenuItemClickListener;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;

public class HomeActivity extends FragmentActivity implements BaseHomeActions, OnPageChangeListener, OnClickListener{
	private final String TAG = HomeActivity.class.getSimpleName();
	private HealthApp mApp = null;
	private ViewPager mHomePager = null;
	private ArrayList<FocusFragment> mPages = null;
	private HashMap<String,Integer> mPageIndexMap = new HashMap<String,Integer>();
	private FragmentStatePagerAdapter mPagerAdapter = null;
	private FragmentManager mFm = null;
	private int pageIndex = 0;
	private final String PAGE_LOC_HOME = "PAGE_LOC_HOME";
	private final String PAGE_HEALTH_HOME = "PAGE_HEALTH_HOME";
	private final String PAGE_HEALTH_SCHEDULE = "PAGE_HEALTH_SCHEDULE";
	private final String PAGE_ACCOUNT = "PAGE_ACCOUNT";
	private final String PAGE_FAMILY = "PAGE_FAMILY";
	
	private BeautyButton to_home;
	private BeautyButton to_schedule;
	private BeautyButton to_account;
	private BeautyButton to_fa;
	
	private String enterType;
	private String trans_type;
	private String trans_param;
	
	private ArrayList<TODO_DATA> mToDoArray = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		logd("onCreate");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		Intent si = new Intent(this, NetService.class);
		si.setAction(NetService.INVOKE_BY_ME);
		startService(si);
		
		setContentView(R.layout.home_activity);
		
		Intent trans = getIntent();
		enterType = trans.getStringExtra("enter_type");
		mApp.setEnterType(enterType);
		if(trans.hasExtra("from") && trans.hasExtra("type") && trans.hasExtra("param")){
			trans_type = trans.getStringExtra("type");
			trans_param = trans.getStringExtra("param");
		}
		
		to_home = (BeautyButton)findViewById(R.id.to_home);
		if(enterType.equals(IndexActivity.ENTER_LOCATION)){
			to_home.setImageSet(getResources().getDrawable(R.drawable.to_map));
			to_home.setText(R.string.loca_home);
		}else if(enterType.equals(IndexActivity.ENTER_HEALTH)){
			to_home.setImageSet(getResources().getDrawable(R.drawable.to_health));
			to_home.setText(R.string.to_health);
		}
		to_home.setColorList(getResources().getColorStateList(R.color.home_but));
		to_home.setOnClickListener(this);
		
		to_schedule = (BeautyButton)findViewById(R.id.to_schedule);
		to_schedule.setImageSet(getResources().getDrawable(R.drawable.to_schedule));
		to_schedule.setColorList(getResources().getColorStateList(R.color.home_but));
		to_schedule.setOnClickListener(this);
		if(enterType.equals(IndexActivity.ENTER_LOCATION)){
			to_schedule.setVisibility(View.GONE);
		}else if(enterType.equals(IndexActivity.ENTER_HEALTH)){
			//to_schedule.setVisibility(View.VISIBLE);
			to_schedule.setVisibility(View.GONE); //remove schedule page for first release
		}
		
		to_account = (BeautyButton)findViewById(R.id.to_account);
		to_account.setImageSet(getResources().getDrawable(R.drawable.to_card));
		to_account.setColorList(getResources().getColorStateList(R.color.home_but));
		to_account.setOnClickListener(this);
		
		to_fa = (BeautyButton)findViewById(R.id.to_family);
		to_fa.setImageSet(getResources().getDrawable(R.drawable.to_fa));
		to_fa.setColorList(getResources().getColorStateList(R.color.home_but));
		to_fa.setOnClickListener(this);
		
		mHomePager = (ViewPager)findViewById(R.id.home_pager);
		
		mPages = new ArrayList<FocusFragment>();
		
		mFm = getSupportFragmentManager();
		
		mPagerAdapter = new FragmentStatePagerAdapter(mFm){

			@Override
			public Fragment getItem(int pos) {
				return mPages.get(pos);
			}

			@Override
			public int getCount() {
				return mPages.size();
			}
			
			@Override
			public int getItemPosition(Object object){
				return PagerAdapter.POSITION_NONE;
			}
		};
		
		mHomePager.setOnPageChangeListener(this);
		mHomePager.setAdapter(mPagerAdapter);
		
		if(enterType.equals(IndexActivity.ENTER_LOCATION)){
			FocusFragment f = new LocateHomeFragment();
			mPages.add(f);
			mPageIndexMap.put(PAGE_LOC_HOME, 0);
		}else if(enterType.equals(IndexActivity.ENTER_HEALTH)){
			FocusFragment f = new HealthHomeFragment();
			mPages.add(f);
			mPageIndexMap.put(PAGE_HEALTH_HOME, 0);
		}
		
		updateMorePages();
		mHomePager.setCurrentItem(pageIndex);
		
		mApp.loadADInfo(false);
	}
	
	@Override
	public void onSaveInstanceState(Bundle b){
		
	}
	
	private void updateMorePages(){
		if(mApp.isUserSignIn()){
			if(mPages.size() == 1){
				int index = mPages.size();
				if(enterType.equals(IndexActivity.ENTER_HEALTH)){
					//remove schedule page for first release
					//FocusFragment f = new HealthScheduleFragment();
					//mPages.add(f);
					//mPageIndexMap.put(PAGE_HEALTH_SCHEDULE, index);
					//index ++;
				}
				FocusFragment af = new AccountFragment();
				mPages.add(af);
				mPageIndexMap.put(PAGE_ACCOUNT, index);
				index ++;
				
				FocusFragment ff = new FamilyFragment();
				mPages.add(ff);
				mPageIndexMap.put(PAGE_FAMILY, index);
			}
		}else{
			//pageIndex = PINDEX_HOME;
			//mHomePager.setCurrentItem(pageIndex,false);
			pageIndex = 0;
			setAccountButtonNum(0);
			mHomePager.setCurrentItem(pageIndex,false);
			int size = mPages.size();
			
			if(size > 1){
				Integer pos = mPageIndexMap.get(PAGE_FAMILY);
				FocusFragment rf = null;
				if(pos != null){
					rf = mPages.get(pos);
				}
				
				pos = mPageIndexMap.get(PAGE_ACCOUNT);
				FocusFragment ra = null;
				if(pos != null){
					ra = mPages.get(pos);
				}
				
				pos = mPageIndexMap.get(PAGE_HEALTH_SCHEDULE);
				FocusFragment rs = null;
				if(pos != null){
					rs = mPages.get(pos);
				}
				
				if(rf != null){
					mPages.remove(rf);
					mPageIndexMap.remove(PAGE_FAMILY);
				}
				
				if(ra != null){
					mPages.remove(ra);
					mPageIndexMap.remove(PAGE_ACCOUNT);	
				}
				
				if(rs != null){
					mPages.remove(rs);
					mPageIndexMap.remove(PAGE_HEALTH_SCHEDULE);
				}
			}
		}
		mPagerAdapter.notifyDataSetChanged();
		mHomePager.invalidate();
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(HealthApp.ACTION_SIGN_IN_OUT)){
				boolean in = intent.getBooleanExtra("state", false);
				if(in == false){
					if(mApp.isUserSignIn()){
						Toast.makeText(HomeActivity.this, R.string.network_err, Toast.LENGTH_LONG).show();
					}
				}
				updateMorePages();
			}else if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				if(t.equals(DataManager.F_TODO)){
					checkTODOData();
				}
				Integer pos = mPageIndexMap.get(PAGE_HEALTH_HOME);
				if(pos != null){
					HealthHomeFragment f = (HealthHomeFragment) mPages.get(pos);
					if(f != null)
						f.dataUpdate(intent);
				}
				
				pos = mPageIndexMap.get(PAGE_ACCOUNT);
				if(pos != null){
					AccountFragment f = (AccountFragment) mPages.get(pos);
					if(f != null)
						f.dataUpdate(intent);
				}
				
				pos = mPageIndexMap.get(PAGE_FAMILY);
				if(pos != null){
					FamilyFragment f = (FamilyFragment) mPages.get(pos);
					if(f != null)
						f.dataUpdate(intent);
				}
			}else if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				String type = intent.getStringExtra("type");
				if(type.equals(DataManager.F_FAMILYLIST)){
					Integer pos = mPageIndexMap.get(PAGE_FAMILY);
					if(pos != null){
						FamilyFragment f = (FamilyFragment) mPages.get(pos);
						if(f != null)
							f.dataUpdate(intent);
					}
				}else if(type.equals(DataManager.F_FAMILYMEMBER)){
					Integer pos = mPageIndexMap.get(PAGE_FAMILY);
					if(pos != null){
						FamilyFragment f = (FamilyFragment) mPages.get(pos);
						if(f != null)
							f.dataUpdate(intent);
					}
				}
			}
		}
	};
	
	private void checkTODOData(){
		if(mApp.isSignIn()){
			grabTodo(mApp);
		}
	}
	
	@Override
	public void onResume(){
		logd("onResume");
		super.onResume();
		
		checkTODOData();
		FocusFragment f = mPages.get(pageIndex);
		f.setFocused(true);
		
		updateBottomButtons();
		mApp.checkNetwork();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(HealthApp.ACTION_SIGN_IN_OUT);
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		//filter.addAction(HealthApp.ACTION_AD_UPDATE);
		registerReceiver(mReceiver, filter);
		
		if((trans_type != null) && (trans_type.trim().length() > 0)){
			Message m = mHandler.obtainMessage(MSG_CHECK_TRANSIT_PARAM);
			mHandler.sendMessageDelayed(m, 200);
		}
		if(mApp.isSignIn()){
			Message m = mHandler.obtainMessage(MSG_REFRESH_TODO);
			mHandler.sendMessageDelayed(m, 10 * 1000);
		}
	}
	
	@Override
	public void onPause(){
		super.onPause();
		logd("onPause");
		FocusFragment f = mPages.get(pageIndex);
		f.setFocused(false);
		unregisterReceiver(mReceiver);
		mHandler.removeMessages(MSG_REFRESH_TODO);
		if(mPopMenu != null){
			mPopMenu.dismiss();
		}
	}
	
	private void updateBottomButtons(){
		if(enterType.equals(IndexActivity.ENTER_LOCATION)){
			Integer pos = mPageIndexMap.get(PAGE_LOC_HOME);
			to_home.setFocused(pageIndex == pos);
		}else if(enterType.equals(IndexActivity.ENTER_HEALTH)){
			Integer pos = mPageIndexMap.get(PAGE_HEALTH_HOME);
			to_home.setFocused(pageIndex == pos);
			
			pos = mPageIndexMap.get(PAGE_HEALTH_SCHEDULE);
			if(pos != null){
				to_schedule.setFocused(pageIndex == pos);
			}else{
				to_schedule.setFocused(false);
			}
		}
		
		Integer pos = mPageIndexMap.get(PAGE_ACCOUNT);
		if(pos != null){
			to_account.setFocused(pageIndex == pos);
		}else{
			to_account.setFocused(false);
		}
		
		pos = mPageIndexMap.get(PAGE_FAMILY);
		if(pos != null){
			to_fa.setFocused(pageIndex == pos);
		}else{
			to_fa.setFocused(false);
		}
	}
	
	@Override
	public void setAccountButtonNum(int num){
		to_account.setMsgCount(num);
	}
	
	public void setFamilyButtonNum(int num){
		to_fa.setMsgCount(num);
	}
	
	public ArrayList<TODO_DATA>  getToDoArray(){
		return mToDoArray;
	}
	
	public class ToDoTimeComparator implements Comparator<Object>{
		@Override
		public int compare(Object arg0, Object arg1) {
			TODO_DATA one = (TODO_DATA)arg0;
			TODO_DATA two = (TODO_DATA)arg1;
			
			int flags = 0;
			if (one.time < two.time) {
				flags = -1;
			}else if(one.time > two.time) {
				flags = 1;
			}else{
				flags = 0;
			}
			return flags;
		}
	}
	
	private void grabTodo(HealthApp app){
		if(app == null)
			return;
		mToDoArray = (ArrayList<TODO_DATA>) app.getDataManager().checkData(DataManager.F_TODO, null);
		int size = mToDoArray.size();
		if(size > 1){
			TODO_DATA[] ds = new TODO_DATA[size];
			ds = mToDoArray.toArray(ds);
			Arrays.sort(ds,0,size,new ToDoTimeComparator());
			
			mToDoArray.clear();
			for(TODO_DATA d:ds){
				mToDoArray.add(d);
			}
		}
		
		setAccountButtonNum(size);
	}
	
	@Override
	public void onDestroy(){
		logd("onDestroy");
		mApp.releaseAllAD();
		mApp.releaseAllData();
		super.onDestroy();
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPageSelected(int pos) {
		logd("onPageSelected " + pos);
		FocusFragment old = mPages.get(pageIndex);
		old.setFocused(false);
		pageIndex = pos;
		FocusFragment f = mPages.get(pageIndex);
		f.setFocused(true);
		Integer faPos = mPageIndexMap.get(PAGE_FAMILY);
		if(faPos != null){
			if(faPos == pageIndex){
				((FamilyFragment)f).buildAFamily(false);
			}
		}
		
		updateBottomButtons();
	}
	
	private boolean clearRefreshingState(){
		FocusFragment f = mPages.get(pageIndex);
		return f.cancelRefresh();
	}
	
	private int RESULT_CODE_SIGN_IN = 22;
	private int RESULT_CODE_SETTINGS = 23;
	private int RESULT_CODE_QRSCAN = 25;
	private int RESULT_CODE_TODO = 26;
	//private int RESULT_CODE_INDEX = 27;
	
	@Override
	public void quitToIndexActivity(){
		Intent i = new Intent(this,IndexActivity.class);
		//i.putExtra("backto", IndexActivity.ENTER_LOCATION);
		startActivity(i);
		finish();
	}

	public void openMapActivity(){
		Intent i = new Intent(this,MapActivity.class);
		startActivity(i);
	}	

	@Override
	public void enterSignIn(){
		Intent i = new Intent(this,SignInActivity.class);
		startActivityForResult(i, RESULT_CODE_SIGN_IN);
	}
	
	
	@Override
	public void openSettings(String from, String fid){
		Intent i = new Intent(this,SettingActivity.class);
		i.putExtra("from", from);
		i.putExtra("fid", fid);
		startActivityForResult(i, RESULT_CODE_SETTINGS);
	}
	
	@Override
	public void openUserDetail(String from){
		if(from.equals("my_data")){
			Intent i = new Intent(this,UserDetailActivity.class);
			startActivity(i);
		}
	}
	
	public void openQRCodeShareWin(String type, String uri, int res){
		Intent i = new Intent(this,QRCodeActivity.class);
		i.putExtra("type", type);
		i.putExtra("uri", uri);
		i.putExtra("mid",res);
		startActivity(i);
	}
	
	public void openQRCodeShareWin(String type, String uri){
		openQRCodeShareWin(type, uri, -1);
	}
	
	@Override
	public void openQRScanerWin(){
		Intent i = new Intent(this,QRScanerActivity.class);
		startActivityForResult(i, RESULT_CODE_QRSCAN);
	}
	
	@Override
	public void openCardsActivity(String indicated){
		Intent i = new Intent(this,CardsActivity.class);
		
		if(indicated == null){
			SharedPreferences p = getSharedPreferences(SettingsConstants.GENERAL_SETTING, MODE_PRIVATE);
			String last = p.getString(SettingsConstants.KEY_CARD_VIEW_TID, "");
			i.putExtra("indicated", last);
		}else{
			i.putExtra("indicated", indicated);
		}
		startActivity(i);
	}
	
	@Override
	public void openToDoActivity(TODO_DATA data){
		Intent i = new Intent(this,ToDoActivity.class);
		//i.putExtra("info", info);
		i.putExtra("data", data);
		
		startActivityForResult(i, RESULT_CODE_TODO);
	}
	
	private void showFamilyApplyPopWin(String fid,String fname){
		ApplyFamilyDialog.open(this, fid, fname, new OnApplyDialogDismissListener(){
			@Override
			public void onDismiss(boolean toBeApply, FMEM_DATA data) {
				if(toBeApply && (data != null)){
					mApp.showWaitting(HomeActivity.this, null);
					
					Intent si = new Intent(HomeActivity.this, NetService.class);
					si.setAction(NetService.APPLY_JOIN_FAMILY);
					si.putExtra("uid", data.uid);
					si.putExtra("fid", data.fid);
					si.putExtra("familystatus", data.status);
					Time t = new Time();
					t.setToNow();
					String stamp = "APPLY_JOIN_FAMILY" + t.toString(); 
					si.putExtra("stamp",stamp);
					mApp.addNetHandler(stamp,mHandler);
					startService(si);
				}
			}
			
		});
	}
	
	private void showDeviceInterestPopWin(final String tid,String dname){
		InterestDeviceDialog.open(this, tid, dname, new OnInterestDialogDismissListener(){

			@Override
			public void onDismiss(boolean toBeApply, DEV_DATA data) {
				if(toBeApply && (data != null)){
					mApp.showWaitting(HomeActivity.this, null);
					
					Intent si = new Intent(HomeActivity.this, NetService.class);
					si.setAction(NetService.APPLY_INTEREST_DEV);
					si.putExtra("uid", mApp.getUID());
					si.putExtra("interestuid", mApp.getUID());
					si.putExtra("tid", data.id);
					si.putExtra("did", "");
					si.putExtra("devicename", data.name);
					
					Time t = new Time();
					t.setToNow();
					String stamp = "APPLY_INTEREST_DEV" + t.toString(); 
					si.putExtra("stamp",stamp);
					mApp.addNetHandler(stamp,mHandler);
					startService(si);
				}
			}
		});
	}
	
	private void showDeviceAddPopWin(String did){
		Intent i = new Intent(this,NewDeviceActivity.class);
		i.putExtra("did", did);
		startActivity(i);
	}
	
	@Override
	public void onActivityResult(int code, int ret, Intent intent){
		if(RESULT_CODE_SIGN_IN == code){
			if(ret == RESULT_OK){
				updateMorePages();
				Integer pos = mPageIndexMap.get(PAGE_ACCOUNT);
				pageIndex = pos;
				mHomePager.setCurrentItem(pageIndex,false);
			}
		}else if(RESULT_CODE_SETTINGS == code){
			if(ret == RESULT_OK){
				String action = intent.getAction();
				if(action.equals("SIGN_OUT")){
					updateMorePages();
					
					Message m = mHandler.obtainMessage(MSG_OPEN_SIGNIN_DELAY);
					mHandler.sendMessageDelayed(m, 300);
					mApp.releaseAllData();
					//means sign out already
				}else if(action.equals("BUILD_FA")){
					Integer faPos = mPageIndexMap.get(PAGE_FAMILY);
					if(faPos != null){
						FamilyFragment ff = (FamilyFragment) mPages.get(faPos);
						if(ff != null){
							ff.buildAFamily(true);
						}
					}
				}else if(action.equals("QUIT_FA")){
					Integer faPos = mPageIndexMap.get(PAGE_FAMILY);
					if(faPos != null){
						FamilyFragment ff = (FamilyFragment) mPages.get(faPos);
						if(ff != null){
							ff.quitFamily();
						}
					}
				}
			}
		}else if(RESULT_CODE_TODO == code){
			if(ret == RESULT_OK){
				String act = intent.getAction();
				if(act.equalsIgnoreCase("Dealed")){
					checkTODOData();
					Integer acPos = mPageIndexMap.get(PAGE_ACCOUNT);
					if(acPos != null){
						AccountFragment af = (AccountFragment) mPages.get(acPos);
						if(af != null){
							af.updateTODO();
						}
					}
				}else if(act.equalsIgnoreCase("CheckDevice")){
					String tid = intent.getStringExtra("tid");
					String c = intent.getStringExtra("code");
					
					if(c.equals("0401")){
						openMapActivity();
					}else if(c.equals("0402")){
						openCardsActivity(tid);
					}
				}
			}
		}else if(RESULT_CODE_QRSCAN == code){
			if(ret == RESULT_OK){
				boolean recognized = false;
				final String uri = intent.getAction();
				if(HttpConf.mine(uri)){
					if(mApp.isUserSignIn() == false){
						mApp.showConfirmDialog(this, getResources().getString(R.string.loginfirst), new View.OnClickListener(){

							@Override
							public void onClick(View v) {
								if(v.getId() == R.id.alert_but1){
									if(!mApp.isUserSignIn()){
										enterSignIn();
									}
								}
							}
							
						});
						return;
					}
					if(uri.contains("action=invite2fa")){
						HashMap<String, String> map = HttpConf.parse(uri);
						String fid = map.get("fid");
						String fname = map.get("fname");
						String dfname = null;
						if(fname != null){
							try {
								dfname = URLDecoder.decode(fname, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								dfname = null;
							}
						}
						if((dfname != null) && (fid != null) && (fid.trim().isEmpty() == false))
							showFamilyApplyPopWin(fid, dfname);
						
						recognized = true;
						return;
					}else if(uri.contains("action=interestdev")){
						HashMap<String, String> map = HttpConf.parse(uri);
						String tid = map.get("tid");
						String dname = map.get("dname");
						String ddname = null;
						if(dname != null){
							try {
								ddname = URLDecoder.decode(dname, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								ddname = null;
							}
						}
						
						if((ddname != null) && (tid != null) && (tid.trim().isEmpty() == false)){
							showDeviceInterestPopWin(tid, ddname);
						}
						recognized = true;
						return;
					}else if(uri.contains("action=adddev")){
						HashMap<String, String> map = HttpConf.parse(uri);
						String did = map.get("did");
						if((did != null) && (did.trim().isEmpty() == false)){
							showDeviceAddPopWin(did);
						}
						recognized = true;
						return;
					}
				}
				if(!recognized){
					String visitweb = getResources().getString(R.string.webvisit, uri);
					mApp.showConfirmDialog(this, visitweb, new View.OnClickListener(){

						@Override
						public void onClick(View v) {
							if(v.getId() == R.id.alert_but1){
								String visit = uri.toLowerCase();
								if(visit.startsWith("http") == false){
									visit = "http://"+visit;
								}
								Uri weburi = Uri.parse(visit);
								Intent intent = new Intent(Intent.ACTION_VIEW, weburi);
								intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(intent);
							}
						}
						
					});
				}
			}
		}
	}
	
	@Override
	public void moveToPre(){
		if(pageIndex > 0){
			pageIndex --;
			mHomePager.setCurrentItem(pageIndex,true);
		}
	}
	
	@Override
	public void moveToNext(){
		int size = mPages.size();
		if(pageIndex < (size - 1)){
			pageIndex ++;
			mHomePager.setCurrentItem(pageIndex,true);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.to_home:{
			//pageIndex = 0;
			mHomePager.setCurrentItem(0,false);
		}
		break;
		case R.id.to_schedule:{
			if(false == enterType.equals(IndexActivity.ENTER_HEALTH)){
				break;
			}
			if(mApp.isUserSignIn()){
				Integer scPos = mPageIndexMap.get(PAGE_HEALTH_SCHEDULE);
				if(scPos != null){
					int index = scPos;
					mHomePager.setCurrentItem(index,false);
				}
			}else{
				enterSignIn();
			}
		}break;
		case R.id.to_account:{
			if(mApp.isUserSignIn()){
				Integer acPos = mPageIndexMap.get(PAGE_ACCOUNT);
				if(acPos != null){
					int index = acPos;
					mHomePager.setCurrentItem(index,false);
				}
			}else{
				enterSignIn();
			}
		}
		break;
		case R.id.to_family:{
			if(mApp.isUserSignIn()){
				Integer faPos = mPageIndexMap.get(PAGE_FAMILY);
				if(faPos != null){
					int index = faPos;
					mHomePager.setCurrentItem(index,false);
				}
			}else{
				enterSignIn();
			}
		}
		break;
		}
	}
	
	//private Toast mQuitToast = null;
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
	   	
	   	if(keyCode == KeyEvent.KEYCODE_BACK){
	   		if(clearRefreshingState()){
	   			return true;
	   		}
	   		
	   		quitToIndexActivity();
	   		/*if(mQuitToast == null){
	   			mQuitToast = Toast.makeText(this, R.string.quit_hint, Toast.LENGTH_LONG);
	   			mQuitToast.show();
	   			mHandler.removeMessages(MSG_DOUBLE_BACK_CHECK);
	   			Message m = mHandler.obtainMessage(MSG_DOUBLE_BACK_CHECK);
	   			mHandler.sendMessageDelayed(m, 3000);
	   		}else{
	   			mQuitToast.cancel();
	   			mQuitToast = null;
	   			mApp.releaseAllAD();
	   			mApp.releaseAllData();
	   			finish();
	   		}*/
	   		return true;
	   	}
	   	return super.onKeyDown(keyCode,event);
    }
	
	//private final int MSG_DOUBLE_BACK_CHECK = 202;
	private final int MSG_OPEN_SIGNIN_DELAY = 203;
	private final int MSG_CHECK_TRANSIT_PARAM = 204;
	private final int MSG_REFRESH_TODO = 205;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_REFRESH_TODO:{
				if(mApp.isSignIn()){
				logd("refresh TODO data");
				mApp.getDataManager().refreshData(DataManager.F_TODO);
				}
			}break;
			case MSG_CHECK_TRANSIT_PARAM:{
				if(trans_type != null){
					if(trans_type.equalsIgnoreCase("TODO")){
						if(mApp.isUserSignIn()){
							checkTODOData();
							Integer acPos = mPageIndexMap.get(PAGE_ACCOUNT);
							if(acPos != null){
								pageIndex = acPos;
								mHomePager.setCurrentItem(pageIndex,true);
								AccountFragment af = (AccountFragment) mPages.get(acPos);
								if(af != null){
									af.enterTodo(trans_param);
								}
							}
						}else{
							enterSignIn();
						}
					}
					trans_type = null;
					trans_param = null;
				}
			}break;
			/*case MSG_DOUBLE_BACK_CHECK:{
				if(mQuitToast != null){
					mQuitToast.cancel();
					mQuitToast = null;
				}
			}
			break;*/
			
			case MSG_OPEN_SIGNIN_DELAY:{
				enterSignIn();
			}break;
			
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("APPLY_JOIN_FAMILY")){
					mApp.dismissWaiting();
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									//TODO:show apply ok
									String txt = getResources().getString(R.string.applyfa_ok);
									mApp.showAlertDialog(HomeActivity.this, txt, R.string.Yes, null);
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.showAlertDialog(HomeActivity.this, R.string.apply_failed);
					}
				}else if(stamp.startsWith("APPLY_INTEREST_DEV")){
					mApp.dismissWaiting();
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									//TODO:show apply ok
									String txt = getResources().getString(R.string.applydev_ok);
									mApp.showAlertDialog(HomeActivity.this, txt, R.string.Yes, null);
									return;
								}else if(state.equals("27")){
									mApp.showAlertDialog(HomeActivity.this, R.string.applydev_noadmin);
									return;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.showAlertDialog(HomeActivity.this, R.string.apply_failed);
					}
				}
			}
			break;
			}
		}
	};
	
	
	private final int POP_MENU_ID_SHARE = 10;
	private final int POP_MENU_ID_SCAN = 11;
	private RightSidePopMenu mPopMenu = null;
	
	@Override
	public void openPopMenu(final String curFrag, View anchor){
		if(mPopMenu != null){
			Log.e(TAG, "openPopMenu mPopMenu != null");
		}
		ArrayList<RightSidePopMenu.Item> items = new ArrayList<RightSidePopMenu.Item>();
		int bg_res = R.drawable.pop_menu_bg;
		int share_icon = R.drawable.share_menu_icon;
		int scan_icon = R.drawable.scan_menu_icon;
		if(enterType.equals(IndexActivity.ENTER_HEALTH)){
			share_icon = R.drawable.health_share_menu_icon;
			scan_icon = R.drawable.health_scan_menu_icon;
		}
		
		if(curFrag.equalsIgnoreCase("home")){
			//分享app
			//扫码
			items.add(new RightSidePopMenu.Item(share_icon, R.string.menu_share, POP_MENU_ID_SHARE));
			items.add(new RightSidePopMenu.Item(scan_icon, R.string.menu_scan, POP_MENU_ID_SCAN));
		}else if(curFrag.equalsIgnoreCase("family")){
			//分享家庭码
			//扫码
			items.add(new RightSidePopMenu.Item(share_icon/*R.drawable.share_menu_icon_w*/, R.string.menu_share_fa, POP_MENU_ID_SHARE));
			items.add(new RightSidePopMenu.Item(scan_icon, R.string.menu_scan, POP_MENU_ID_SCAN));
			//bg_res = R.drawable.pop_menu_bg_blue;
		}else if(curFrag.equalsIgnoreCase("account")){
			items.add(new RightSidePopMenu.Item(scan_icon, R.string.menu_scan, POP_MENU_ID_SCAN));
			bg_res = R.drawable.pop_menu_bgsingle;
		}
		
		mPopMenu = new RightSidePopMenu(HomeActivity.this, items);
		mPopMenu.setBackground(bg_res);
		mPopMenu.setOnPopMenuItemClickListener(new OnPopMenuItemClickListener(){

			@Override
			public boolean onPopMenuItemClick(int ID) {
				switch(ID){
				case POP_MENU_ID_SHARE:{
					if(curFrag.equalsIgnoreCase("home")){
						openQRCodeShareWin(QRCodeActivity.TYPE_APK, HttpConf.getApkUri(),R.drawable.app_logo);
					}else if(curFrag.equalsIgnoreCase("family")){
						Integer faPos = mPageIndexMap.get(PAGE_FAMILY);
						if(faPos != null){
							FamilyFragment ff = (FamilyFragment) mPages.get(faPos);
							if(ff != null){
								FA_DATA fa = ff.getCurFaCopy();
								
								if(fa.id != null && !fa.id.trim().isEmpty()){
									String uri = HttpConf.getFamilyInvitationUri(fa.id, fa.name);
									if(uri != null)
										openQRCodeShareWin(QRCodeActivity.TYPE_FAMILY, uri);
								}
							}
						}
					}
				}
				break;
				case POP_MENU_ID_SCAN:{
					openQRScanerWin();
				}
				break;
				}
				return false;
			}
			
		});
		
		mPopMenu.show(anchor);
	}
	
	/*health options begin*/
	public void openHealthCardsActivity(String tid, String subcode){
		Intent i = new Intent(this,HealthCardsActivity.class);
		
		i.putExtra("tid", tid);
		i.putExtra("subcode", subcode);
		startActivity(i);
	}
	/*health options end*/
	
}